<template>
	<div>
		<view>
      <uv-calendars
                :insert="true"
                ref="calendars"
                mode="multiple"
                :date="DefaultTime"
                :startDate="minDate"
                @confirm="confirm"
                @change="time"
            />
		</view>
		<div class="quabbao">
			<div class="sjkuang">
				<div>时段设置<text style="font-size: 16px; color: #707070;">(共{{ tianshu }}天可约)</text></div>
			</div>
			<div class="yuyue" v-for="notice in notices" :key="notice.id">
    <view>
        <div style="font-size: 18px;">{{ notice.nian }}年{{ notice.yuefen }}月{{ notice.rhao }}号 ({{ notice.zhoji }})</div>
    </view>
    <div class="shuipjuz" v-for="(addtime, index) in notice.addtimes" :key="addtime.id">
        <div class="portal">
        <picker mode="time" :value="addtime.time" start="00:00" end="23:59" @change="bindTimeChange" :data-id="`${notice.id},${addtime.id}`">
            <view class="uni-input" style="font-size: 17px;">{{addtime.time}}</view>
        </picker>
        </div>
        <div class="separator">~</div>
        <div class="portal">
        <picker mode="time" :value="addtime.time1" start="00:00" end="23:59" @change="bindTimeChange1" :data-id="`${notice.id},${addtime.id}`">
            <view class="uni-input" style="font-size: 17px;">{{addtime.time1}}</view>
        </picker>
        </div>
        <div class="lajit-wrapper">
            <img src="/static/ljt.png" @click="shancushijian(addtime.id, notice.id)" class="lajit" />
        </div>
        <view class="kaiqi">
            <uv-switch v-model="addtime.switch1Value" activeColor="#00aa00" @change="$event => asyncChange($event)" :data-id="`${notice.id},${addtime.id}`"></uv-switch>
        </view>
    </div>
    <div class="tianjiasj" @click="addTimeSlot(notice.id)">
        + 添加时段
    </div>
</div>
		</div>
		<div style="height: 50px;"></div>
		<!-- <uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确定" title=" " :content="nrtsk" @confirm="dialogConfirm"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup> -->
		<div class="zaitoyj">
			<div class="bubaoc" @click="bubaocsj">
				不保存,返回
			</div>
			<div class="bubaoc" @click="baocsjsuj">
				保存时间设置
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,onMounted,watch,nextTick
	} from 'vue'; // 确保导入的路径与你的项目结构相匹配
	import {
		gonavigateTo
	} from '@/request/wx.js';
    const weekToChinese = (number) => {
    const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weeks[number];
    };
	const notices = ref([]);
    const selectDate= ref([]);
	const addtimes = ref([]);
	const nrtsk = ref('');

	const alertDialog = ref(null);

	const tianshu = ref(1);

	const calendars = ref(null);

	const delid = ref(null);

	const switch1Value = ref(true);
  
  const DefaultTime= ref([]);

	// 创建一个响应式变量来存储最小日期
    const minDate = ref('');
   // 在 mounted 生命周期钩子中获取当前日期并插入数据
   onMounted(() => {
  const data = uni.getStorageSync('adminAddHomemaking');
  const today = new Date();
  minDate.value = today.toISOString().split('T')[0];
  if (data) {
    // 使用 push.apply 方法将 data 中的元素添加到 notices 数组中
    Array.prototype.push.apply(notices.value, data);
    tianshu.value=data.length;
    const datesArray = data.map(item => {
      return `${item.nian}-${item.yuefen.toString().padStart(2, '0')}-${item.rhao.toString().padStart(2, '0')}`;
    });
    console.log(datesArray)
    DefaultTime.value = datesArray;
    for (let i = 0; i < datesArray.length; i++) {
      selectDate.value.push(datesArray[i]);
    }
  } else {
    DefaultTime.value = today.toISOString().split('T')[0];
    // 插入默认数据
    const todayDate = {
      fulldate: minDate.value,
      lunar: {
        cYear: today.getFullYear(),
        cMonth: today.getMonth() + 1,
        cDay: today.getDate(),
        ncWeek: weekToChinese(today.getDay())
      }
    };
    selectDate.value.push(todayDate.fulldate);
    const newNotice = {
      id: notices.value.length + 1,
      nian: todayDate.lunar.cYear,
      yuefen: todayDate.lunar.cMonth,
      rhao: todayDate.lunar.cDay,
      zhoji: todayDate.lunar.ncWeek,
      addtimes: [{
        id: addtimes.value.length + 1,
        time: '10:00',
        time1: '10:59',
        switch1Value: true
      }]
    };
    notices.value.push(newNotice);
  }
});

const shancushijian = (id, noticeId) => {
    const notice = notices.value.find(notice => notice.id === noticeId);
    const index = notice.addtimes.findIndex(addtime => addtime.id === id);
    if (index !== -1) {
        notice.addtimes.splice(index, 1);
    }
    // delid.value = id;
    // nrtsk.value = "是否要删除该时间段?";
    // alertDialog.value.open();
}

	const bubaocsj = () => { //不保存，返回
		gonavigateTo(`/pages/admin/homemaking/add/settings`);
	}

	const baocsjsuj = () => { //保存时间设置
    for(let i=0; i<notices.value.length; i++){
      if(notices.value[i].addtimes.length==0){
        uni.showToast({
          title: '请设置时间段',
          icon: 'none'
        });
        return 
      }
    }
    uni.setStorageSync('adminAddHomemaking', notices.value);
    uni.redirectTo({
      url: '/pages/admin/homemaking/add/settings'
    });
    
	}

    const addTimeSlot = (noticeId) => {
  // 首先，找到对应的 notice 对象
  const notice = notices.value.find(notice => notice.id === noticeId);
  
  // 检查是否找到了对应的 notice 对象
  if (!notice) {
    console.error('Notice not found');
    return;
  }

  // 确保 notice 对象有 addtimes 数组
  if (!notice.addtimes) {
    notice.addtimes = [];
  }

  // 创建新的时间槽对象
  const newTimeSlot = {
    id: notice.addtimes.length + 1,
    time: '10:00',
    time1: '10:59',
    switch1Value: true
  };

  // 将新的时间槽添加到对应的 notice 对象的 addtimes 数组中
  notice.addtimes.push(newTimeSlot);
};

    function bindTimeChange(event) {
  const [noticeId, addtimeId] = event.target.dataset.id.split(',');
  const notice = notices.value.find(notice => notice.id === parseInt(noticeId));
  const addtime = notice?.addtimes?.find(addtime => addtime.id === parseInt(addtimeId));
  const newTime = event.detail.value;
    console.log(addtime)
  if (addtime) {
    // 检查新选择的时间是否小于结束时间
    if (newTime >= addtime.time1) {
      // 时间选择有误，不更新时间，并提示用户
      uni.showToast({
        title: '开始时间必须小于结束时间',
        icon: 'none'
      });
      // 恢复到之前的时间
    //   addtime.time = addtime.oldTime || newTime;
    } else {
      // 时间选择正确，更新时间并保存当前时间以便下次比较
      addtime.oldTime = addtime.time;
      addtime.time = newTime;
    }
  }
}

function bindTimeChange1(event) {
  const [noticeId, addtimeId] = event.target.dataset.id.split(',');
  const notice = notices.value.find(notice => notice.id === parseInt(noticeId));
  const addtime = notice?.addtimes?.find(addtime => addtime.id === parseInt(addtimeId));
  const newTime1 = event.detail.value;

  if (addtime) {
    // 检查新选择的结束时间是否大于开始时间
    if (newTime1 <= addtime.time) {
      // 时间选择有误，不更新时间，并提示用户
      uni.showToast({
        title: '结束时间必须大于开始时间',
        icon: 'none'
      });
      // 恢复到之前的时间
    //   addtime.time1 = addtime.oldTime1 || newTime1;
    } else {
      // 时间选择正确，更新时间并保存当前时间以便下次比较
      addtime.oldTime1 = addtime.time1;
      addtime.time1 = newTime1;
    }
  }
}

function asyncChange(event) {
    // 更新对应的 switch1Value
    if (!event) {
      uni.showModal({
        content: '是否要停止该时间段的预约? 停止后, 已有预约记录仍将保留',
        success: (res) => {
        }
      });
    } else {
    }
}
    function time(e) {
    console.log(e);
    console.log(e.fulldate)
    console.log(selectDate.value);
    // 检查 selectDate 数组中是否已经存在当前选择的日期
    const dateIndex = selectDate.value.findIndex(date => date === e.fulldate);
    console.log(dateIndex)
    if (dateIndex !== -1) {
            // 如果存在，从 selectDate 和 notices 数组中删除对应的数据
            selectDate.value.splice(dateIndex, 1);
            const noticeIndex = notices.value.findIndex(notice => 
                notice.nian === e.lunar.cYear &&
                notice.yuefen === e.lunar.cMonth &&
                notice.rhao === e.lunar.cDay
            );
            console.log(noticeIndex)
            if (noticeIndex !== -1) {
                notices.value.splice(noticeIndex, 1);
            }
            tianshu.value=tianshu.value-1
        } else {
            // 如果不存在，则添加新的日期和 notice 对象
            selectDate.value.push(e.fulldate);
            const newNotice = {
                id: notices.value.length + 1,
                nian: e.lunar.cYear,
                yuefen: e.lunar.cMonth,
                rhao: e.lunar.cDay,
                zhoji: e.lunar.ncWeek,
                addtimes:[{
                  id: addtimes.value.length + 1,
                  time: '10:00',
                  time1: '10:59',
                  switch1Value: true
                }], // 为每个 notice 创建一个新的 addtimes 数组
                //switch1Value: true // 为每个 notice 创建一个新的 switch1Value
            };
            tianshu.value=tianshu.value+1
            notices.value.push(newNotice);
        }
    }
</script>

<style scoped>
	.sjkuang {
		border: 1px solid #e8e8e8;
		/* 边框颜色和宽度 */
		padding: 15px;
		/* 内边距 */
		width: 91%;
		/* 宽度 */
		text-align: center;
		/* 文本居中 */
		font-size: 20px;
		/* 字体大小 */
		background-color: #f5f5f5;
		margin-top: 15px;
	}

	.quabbao {
		padding: 10px;
	}

	.yuyue {
		border: 1px solid #d2d2d2;
		/* 边框颜色和宽度 */
		padding: 20px;
		/* 内边距 */
		width: 88%;
		/* 宽度 */
		text-align: center;
		/* 文本居中 */
		font-size: 16px;
		/* 字体大小 */
		background-color: #f5f5f5;
		/* 背景颜色 */
		border-radius: 10px;
		/* 圆角半径 */
		/* font-weight: bold; /* 字体加粗 */
		margin-top: 15px;
	}

	.shuipjuz {
		display: table;
		margin-top: 25px;
		margin-left: 15px;
	}

	.portal,
	.separator,
	.lajit,
	.kaiqi {
		display: table-cell;
		vertical-align: middle;
	}

	.separator {
		text-align: center;
		width: 10px;
		/* 或者你希望的任何宽度 */
		padding-left: 5px;
		/* 左边距 */
		padding-right: 5px;
		/* 右边距 */
		vertical-align: top;
	}

	.lajit-wrapper {
		margin: 6px 16px;
	}

	.lajit {
		width: 23px;
		height: 23px;
	}

	.portal {
		border: 1px solid #cbcbcb;
		/* 边框颜色和宽度 */
		padding: 5px;
		/* 内边距 */
		margin: 10px;
		/* 外边距 */
		width: 66px;
		/* 宽度 */
		height: 20px;
		/* 高度 */
		background-color: #ffffff;
		/* 背景颜色 */
	}

	.tianjiasj {
		color: #1c9399;
		font-size: 18px;
		margin-top: 30px;
		margin-right: 100px;
	}

	/* .zaitoyj {
		width: 100%;
	} */

	.zaitoyj {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		/* padding: 10px 0; */
		box-shadow: 0 -1px 5px rgba(85, 0, 0, 0.1);
	}

	.bubaoc {
		flex: 1;
		background-color: #1c9399;
		transition: background-color 0.3s;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	.bubaoc:first-child {
		background-color: #f64b4d;
	}
</style>